const app = null;
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const FORM = 'FORM';
const DELETE = 'DELETE';

// const baseURL = 'https://carsource.zhejiangzhongzhe.cn/apitst/applet/';
const baseURL = 'https://carsource.zhejiangzhongzhe.cn/api/applet/'
// 配置请求Api如下
const API = {
    //小程序API
    queryBanner: () => request(POST, `app/banner/list`,{},'',false), //查询首页banner图
    // 用户API
    userLogin: (data) => request(POST, `user/login`,{'code':data},'获取用户',false), //用户登录
    userRegApply: (data) => request(POST, `user/reg/apply`,data,'提交申请中'), //申请注册
    userModifylogo:(data) => request(POST, `user/modify/logo`,{'userLogoUrl':data},'正在更改'), //修改头像
    userModifyName:(data) => request(POST, `user/modify/name`,{'userName':data},'正在更改'), //修改姓名
    userModifyWechat:(data) => request(POST, `user/modify/wechat`,{'wechat':data},'正在更改'), //修改微信号
    userModifyMobile:(data) => request(POST, `user/modify/mobile`,data,'正在更改'), //修改手机号
    userRemindRead:(data) => request(POST, `user/remind/read`,{'remindId':data},'',false), //8.提醒已读
    // 车辆API -- 客户口
    carCustSearchSeriesStat:(data) => request(POST, `car/cust/searchSeriesStat`,data,'',false), // 车辆列表，可多条件筛选
    carCustList:(data) => request(POST, `car/cust/list`,data,'为您寻找好车'), // 车辆列表，可多条件筛选
    carCustView:(data) => request(POST, `car/cust/view`,{'carId':data},'获取车辆信息'), //查看车辆详情
    carCustOfferPrice:(data) => request(POST, `car/cust/offerPrice`,data,'正在出价'), //车辆详情中的我要出价
    // 车辆API -- 管理口
    carManageList:(data) => request(POST, `car/manage/list`,data,'获取车辆'), // 车辆列表，可多条件筛选
    ocrDiscern:(data) => request(POST, `ocr/discern`,data,'正在识别'), // 证件识别,接口返回结果有值就填充，没返回值不填充
    carVinList:(data) => request(POST, `car/vin/list`,data,'获取车型'), // 车架号查询,车架号与车辆型不能同时为空
    carVinRefreshList:(data) => request(POST, `car/vin/refreshList`,data,'刷新车型'), // 获取全新的车型
    carManagePublishCar:(data)  => request(POST, `car/manage/publish/car`,data,'正在发布'), //发布车辆
    carManageClearCar:(data)  => request(POST, `car/manage/clearCar`,{'carId':data},'细心擦拭',false), //擦车
    carManageModifyStatus:(data)  => request(POST, `car/manage/modify/status`,data,'正在操作'), //上下架车辆
    carManageDetail:(data) => request(POST, `car/manage/detail`,{'carId':data},'获取车辆信息'), //车辆详情，获取车商自己发布的车辆详情
    carManageModify:(data) => request(POST, `car/manage/modify`,data,'正在提交'),//车辆修改，车架号不能修改
    carManageOfferPriceList:(data) => request(POST, `car/manage/offerPrice/list`,data,'获取出价信息'),//获取出价信息
    carManageOfferPriceHandle:(data) => request(POST, `car/manage/offerPrice/handle`,data,'处理出价中'),//处理中
    // 求购 
    wantBuyPublish:(data) => request(POST, `wantBuy/publish`,data,'正在发布求购'),//发布求购信息
    wantBuyList:(data) => request(POST, `wantBuy/list`,data,'加载中'), // 求购列表
    wantBuySelfList:(data) => request(POST, `wantBuy/self/list`,data,'获取求购列表'), // 我的求购列表
    wantBuySelfModifyStatus:(data)  => request(POST, `wantBuy/self/modify/status`,data,'正在操作'), //上下架求购
    wantBuySelfDetail:(data) => request(POST, `wantBuy/self/detail`,{'buyId':data},'获取求购信息'), //获取求购详情
    wantBuySelfModify:(data) => request(POST, `wantBuy/self/modify`,data,'正在提交'),//求购修改
    // 一口价
    secondBatchPublish:(data) => request(POST, `secondBatch/publish`,data,'正在发布一口价'),//发布一口价信息
    secondBatchList:(data) => request(POST, `secondBatch/list`,data,'加载中'), // 一口价列表
    secondBatchView:(data) => request(POST, `secondBatch/view`,{'secondBatchId':data},'获取一口价信息'), //获取一口价详情
    secondBatchOrderCreate:(data) => request(POST, `secondBatch/order/create`,{'secondBatchId':data},'正在创建订单'), // 创建一口价支付订单
    secondBatchOrderPayResult:(data) => request(POST, `secondBatch/order/payResult`,{'orderNo':data},'查询订单状态'), 
    secondBatchSelfList:(data) => request(POST, `secondBatch/self/list`,data,'获取一口价列表'), // 获取一口价列表
    secondBatchSelfClose:(data)  => request(POST, `secondBatch/self/close`,data,'正在操作'), //关闭一口价
    // 拍卖
    auctionPublish:(data) => request(POST, `auction/publish`,data,'正在发布拍卖'),//发布拍卖信息
    auctionList:(data) => request(POST, `auction/list`,data,'加载中'), // 拍卖列表
    auctionView:(data) => request(POST, `auction/view`,{'auctionId':data},'获取拍卖信息'), //获取拍卖详情
    auctionOrderCreate:(data) => request(POST, `auction/order/create`,{'auctionId':data},'正在创建订单'), // 创建一口价支付订单
    auctionOrderPayResult:(data) => request(POST, `auction/order/payResult`,{'orderNo':data},'查询订单状态'), 
    auctionLatestOffer:(data) => request(POST, `auction/latestOffer`,data,'',false), // 获取最新出价信息
    auctionOffer:(data) => request(POST, `auction/offer`,data,'正在提交竞价'), // 提交竞价
    auctionSelfList:(data) => request(POST, `auction/self/list`,data,'获取拍卖列表'), // 获取拍卖列表

    // 车商API
    dealerInfo:(data) => request(POST, `dealer/info`,data || {},'获取公司信息',false), //用于个人-我的公司信息查看
    dealerModifyBaseInfo:(data) => request(POST, `dealer/modify/baseInfo`,data,'正在提交信息'),//用于个人-我的公司信息-修改信息
    dealerModifyPicList:(data) => request(POST, `dealer/modify/picList`,data,'正在提交资料'), //的公司修改图片
    
    dealerUserList:(data) => request(POST, `dealer/user/list`,data,'获取团队信息'), // 团队列表
    dealerUserModify:(data) => request(POST, `dealer/user/modify`,data,'正在操作'), // 修改团队成员
    dealerUserApplyList:() => request(POST, `dealer/user/applyList`,{},'查询申请人员',false), //申请人员列表，该列表也可用于新申请数量的展示
    dealerUserAuditApply:(data) => request(POST, `dealer/user/auditApply`,data,'正在操作'), // 审批申请
    dealerOrderCreate:(data) => request(POST, `dealer/order/create`,{'orderType':data},'正在创建订单'), // 审批申请
    dealerOrderPayResult:(data) => request(POST, `dealer/order/payResult`,{'orderNo':data},'查询订单状态'), // 
    //消息API
    msgUnreadStat:() => request(POST, `msg/unreadStat`,{},'',false),//获取消息数量 index。
    noticeList:(data) => request(POST, `notice/list`,data,'获取系统消息'), // 通知列表
    noticeRead:(data) => request(POST, `notice/read`,{'noticeId': data},'读取消息'), //通知已读
    //车辆品牌API
    carBrandList: () => request(POST, `car/brand/list`,{},'获取车辆品牌'), //车辆品牌列表
    carBrandSeriseList: (data) => request(POST, `car/brand/series/list`,{'brandId':data},'获取车系列表'), //车辆品牌下车系列表
    carBrandAttentionStat: () => request(POST, `car/brand/attention/stat`,{},'获取关注品牌',false), //用于首页“我的关注”
    carBrandAttentionList: () => request(POST, `car/brand/attention/list`,{},'获取关注列表'), //用于编辑我的关注页面中全部的关注
    carBrandHotList: () => request(POST, `car/brand/hot/list`,{},'获取热门品牌'), //热门品牌列表，取关注量最多的20个品牌
    carBrandAttention: (data) => request(POST, `car/brand/attention`,data,(data.operateType == 1?'正在关注':'取消关注')), //关注/取消关注车辆品牌列表  
    // 公用API
    smsSend: (data) => request(POST, `sms/send`,data,'正在发送验证码'), //发送验证码
    upload: (data) => upload(data), //上传文件
    shareqrCode:(data) => request(POST, `share/qrCode`,data,'获取分享信息'), //获取分享信息

    // 車商賬戶API
    dealerAmountDetailList:(data) => request(POST, `dealer/amount/detail/list`,data,'获取详细',false), //获取详细
    dealerAmountInfo:() => request(POST, `dealer/amount/info`,{},'获取余额'), //获取余额
    dealerAmountRechargePriceList:() => request(POST, `dealer/amount/rechargePrice/list`,{},'获取充值信息',false), //获取充值信息
    dealerAmountOrderCreate:(data) => request(POST, `dealer/amount/order/create`,{'rechargeId':data},'正在创建订单'), // 
    dealerAmountOrderPayResult:(data) => request(POST, `dealer/amount/order/payResult`,{'orderNo':data},'查询订单状态'), // 

    // 维保接口
    reportConfigInfo:() => request(POST, `report/config/info`,{},'获取数据源'), //获取数据源
    reportPrice:(data) => request(POST, `report/price`,data,'获取价格'), //获取价格
    reportOrderCreate:(data) => request(POST, `report/order/create`,data,'正在创建订单'), // 
    reportOrderPayResult:(data) => request(POST, `report/order/payResult`,{'orderNo':data},'查询订单状态'), // 
    reportOrderList:(data) => request(POST, `report/order/list`,data,'获取记录'), // 获取报告订单列表
    reportOrderDetail:(data) => request(POST, `report/order/detail`,{'orderNo':data},'获取订单详情'), // 获取订单详情
    reportOrderPayInfo:(data) => request(POST, `report/order/payInfo`,{'orderNo':data},'获取支付信息'), // 获取支付信息
    reportOrderCancel:(data) => request(POST, `report/order/cancel`,{'orderNo':data},'取消订单'), // 取消报告订单
    reportApply:(data) => request(POST, `report/apply`,data,'申请中'), // 申请中
    reportApplyList:(data) => request(POST, `report/apply/list`,data,'获取列表'), // 申请报告列表
    reportApplyAudit:(data) => request(POST, `report/apply/audit`,data,'操作中'), // 73.报告—审核申请
    
    // 管理模块
    custMagerTaskStatOverview:() => request(POST, `custMager/task/stat/overview`,{},'获取任务'), //77.任务总览统计
    custMagerCarLoanClueList:(data) => request(POST, `car/loanClue/list`,data,'获取列表'), // 获取线索列表
    custMagerCarLoanClueStat:() => request(POST, `car/loanClue/stat`,{},'线索统计'), //79.线索统计
    custMagerCarLoanClueAdd:(data) => request(POST, `car/loanClue/add`,data,'提交线索'), // 提交线索
    carManageLogList:(data) => request(POST, `car/manage/log/list`,data,'获取车辆日志'), 

    //获取车商列表（客户经理接口）
    dealerCustMagerDealerList:() => request(POST, `dealer/custMager/dealerList`,{},'获取车商列表'), //获取车商列表
    custMagerTaskStatDealer:(data) => request(POST, `custMager/task/stat/dealer`,{dealerId:data},'获取车商任务'), 

    // 公告列表
    custMagerNoticeList:(data) => request(POST, `custMager/notice/list`,data,'获取公告信息'), // 公告信息
    custMagerNoticeRead:(data) => request(POST, `custMager/notice/read`,{noticeId:data},'获取公告信息'), 
    // 车商拓展
    custMagerDealerVisitList:(data) => request(POST, `custMager/dealer/visit/list`,data,'获取拓展列表'), // 获取拓展列表
    custMagerDealerBisitAdd:(data) => request(POST, `custMager/dealer/visit/add`,data,'提交拜访信息'), // 提交拜访信息
    
    
};
module.exports = {
    API: API
}
async function request(method, url, data , loadingMsg, loading) {
    let app = getApp();
    let userToken = '';
    if(url != 'user/login'){
        userToken = await app.checkToken();
        // console.log('等待获取Token',userToken);
    }
    undefined == loading?loading = true:'';
    app.requestNumber++;
    return new Promise(function(resolve, reject) {
        let header = {
            'content-type': 'application/json',
            '_v': app.IronVersion,
            '_ov': app.mobileSystem,
            '_om': app.mobileModel,
        };
        url != 'user/login'?header['_t'] = userToken:'';
        loading?app.showLoading(loadingMsg):'';
        wx.request({
            url: baseURL + url,
            method: method,
            data: method === POST ? JSON.stringify(data) : data,
            header: header,
            success(res) {
                app.requestNumber--;
                if(-1 == app.requestNumber){
                    app.requestNumber = -1;
                    // console.log(app.requestNumber);
                    wx.hideLoading();
                }
                //请求成功
                //判断状态码---errCode状态根据后端定义来判断
                if (res.data.rtn == 1) {
                    resolve(res.data);
                } else {
                    // 处理其他问题
                    //其他异常 10001 服务内部错误 10002 普通错误，可直接提示返回的msg内容
                    // 10003 token过期,重新登录获取token 10004 用户被停用 10005 无权限
                    switch (res.data.errCode) {
                        case "10001":
                            res.data.msg = '服务内部错误';
                            reject(res.data);
                            break;
                        case "10002":
                            reject(res.data);
                            if(res.data.msg == '该账号已被停用，请联系管理员'){
                                wx.reLaunch({
                                    url: '/pages/login/login?type=fail',
                            })}
                            //     reject(res.data);
                            // }else{
                            //     reject(res.data);
                            // }
                            break;
                        case "10003":
                            app.showLoginInvalid();
                            res.data.msg = '用户登录信息已失效';
                            // 重新获取Token并重试当前请求。
                            reject(res.data);
                            break;
                        case "10004":
                            wx.reLaunch({
                              url: '/pages/login/login?type=fail',
                            })
                            res.data.msg = '您当前账户已被封禁';
                            // 跳转到封禁页面。
                            reject(res.data);
                            break;
                        case "10005":
                            app.showNoAuthOrNoGrant('您无权进行此操作');
                            res.data.msg = '您无权进行此操作';
                            // 无权提示。
                            reject(res.data);
                            break;
                        default:
                            // 请求出错了。可能状态码有问题。
                            reject('未知错误');
                            break;
                    }
                }
            },
            fail(err) {
                app.requestNumber--;
                if(-1 == app.requestNumber){
                    app.requestNumber = -1;
                    wx.hideLoading();
                }
                //请求失败
                reject(err)
            }
        })
    })
}
async function upload(param) {
    console.log(param);
    let app = getApp();
    let header = {
        '_v': app.IronVersion,
        '_ov': app.mobileSystem,
        '_om': app.mobileModel,
        '_T': await app.checkToken(),
        "Content-Type": "multipart/form-data"
    };
    return new Promise(function(resolve, reject) {
        wx.uploadFile({
            url: baseURL + 'upload/file',
            filePath: param.filePath,
            name: 'file',
            header: header,
            formData:{
              uploadType: param.fileType,
              isNeedThumbnail: param.isNeedThumbnail
            },
            success (res){
                try {
                    resolve(JSON.parse(res.data));
                 }
                 catch (e) {
                     reject('上传文件失败');
                 }
                
            },
            fail (err){
                reject(err);
            }
        })
    })
};